package com.simas.screen;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Keypad;
//import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
//import net.rim.device.api.ui.component.NullField;
//import net.rim.device.api.ui.component.NullField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.GridFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import com.simas.common.CommonFunction;
import com.simas.common.CommonMenu;
import com.simas.common.CustomResources;
import com.simas.common.DeletePolisInfo;
import com.simas.common.XMLWaitProcess;
//import com.simas.common.mbu.CallMBUServlet;
//import com.simas.common.DeletePolisInfo;
//import com.simas.common.OpenInfoScreen;
//import com.simas.common.OpenPolisScreen;
import com.simas.component.CellButton;
import com.simas.component.CustomButton;
import com.simas.mobil.CallMBUServlet;

public class XmlMBUScreen extends MainScreen implements FieldChangeListener {
	CommonFunction cf = new CommonFunction();
	CustomResources cr = new CustomResources();
	private int intIdxScreen = cr.getIntIdxMBUScreen();
	private VerticalFieldManager vfm;
	private CellButton btHome;
	private CellButton btReset;
	private LabelField lblSeparator1;
	
	int intRows = 7;
	int intCols = 3;
	GridFieldManager gfmOrig = new GridFieldManager(intRows,intCols,Field.USE_ALL_WIDTH);
	private int intCekKlaim = 0;
	
	int intKlaimRow = 15;
	int intKlaimCols = 3;
	GridFieldManager gfmKlaim = new GridFieldManager(intKlaimRow,intKlaimCols,Field.USE_ALL_WIDTH);
	
	private String strKondisi;
	private String strKendala;
	private String strKeterangan;
	
	private String strMaxNo;
	private String strRecNo;
	
	private CustomButton btNextKlaim;
	private CustomButton btPrevKlaim;
	
	private String strHidNoRangka;
	private String strHidNoPolis;
	private String strHidNoMesin;
	private String strHidNoPlat;
	private String strRootName;
	
	private static final int _tab = 4;
	
	/**
     * Menambah Menu Close
     */
    protected void makeMenu( Menu menu, int instance ) {
		CommonMenu cm = new CommonMenu(this);
		menu.add(cm._welcomeScreen);
	}
	   
    /**
     * Action utk Back Button
     */
    protected boolean keyDown(int keycode, int status)  {
		if(Keypad.key(keycode) == Keypad.KEY_ESCAPE) {
			CommonMenu cm = new CommonMenu(this);
			cm.welcomeScreen();
			return true;
		}
		return false;
	}
	
    /**
     * Action Listener
     */
	public void fieldChanged(Field field, int context) {
		if (field == btHome) {
			CommonMenu cm = new CommonMenu(this);
			cm.welcomeScreen();
		} else if (field == btReset) {
			//fnResetInfo();
			DeletePolisInfo dpi = new DeletePolisInfo();
			dpi.fnDeletePolis(this, intIdxScreen);
		}
	}
	
	public XmlMBUScreen(String strURL) {
		Bitmap resizeBitmap = cf.getScaledBitmapImage(cr.getImageURL("bgSimasMobil.png"));
		Background bg = BackgroundFactory.createBitmapBackground(resizeBitmap, 
																 Background.POSITION_X_LEFT, 
																 Background.POSITION_Y_TOP, 
																 Background.REPEAT_NONE);

		vfm = new VerticalFieldManager(Field.USE_ALL_WIDTH);
		vfm.setBackground(bg);
		vfm.setFont(cr.getCustomFont(4));
		for (int a=1; a<=7; a++) {
			vfm.add(new LabelField(" ", Field.USE_ALL_WIDTH));
		}
		
		btHome = new CellButton("Home", Integer.parseInt("000000", 16), 
				 Integer.parseInt("FFCC33", 16), 
				 0, null, 0, 0, 0, 0);
		btHome.setFont(cr.getCustomFont());
		btHome.setChangeListener(this);
		
		btReset = new CellButton("Reset", Integer.parseInt("000000", 16), 
				 Integer.parseInt("FFCC33", 16), 
				 0, null, 0, 0, 0, 0);
		btReset.setFont(cr.getCustomFont());
		btReset.setChangeListener(this);
		
		lblSeparator1 = new LabelField(" | ", Field.FIELD_LEFT);
		lblSeparator1.setFont(cr.getCustomFont(5));
		
		HorizontalFieldManager hfmButton = new HorizontalFieldManager(Field.FIELD_HCENTER);
		hfmButton.add(btHome);
		hfmButton.add(lblSeparator1);
		hfmButton.add(btReset);
		
		vfm.add(hfmButton);
		add(vfm);
		
		gfmOrig.setFont(cr.getCustomFont());
		gfmKlaim.setFont(cr.getCustomFont());
		
		XMLWaitProcess xmlwp = new XMLWaitProcess();
		xmlwp.WaitProcess(strURL,"GET", this);
		
	}
	
	/**
	 * request berhasil 
	 */
	public void requestSucceeded(byte[] result, String contentType) {
		if (contentType.startsWith("text/")) {
			synchronized (UiApplication.getEventLock()) {
				
				String strResult = new String(result);
				try {
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		            DocumentBuilder builder = factory.newDocumentBuilder();
		            InputStream inputStream = new ByteArrayInputStream(strResult.getBytes());
		            Document document = builder.parse( inputStream );
		            Element rootElement = document.getDocumentElement();
		            rootElement.normalize();
		            
		            vfm.add(new LabelField(" ", Field.USE_ALL_WIDTH));
		            
		    		displayNode( rootElement, 0 );
		            
		            // data peserta
		    		HorizontalFieldManager hfmPeserta = cr.getHeaderRibbon("DATA PESERTA", 0);
		    		hfmPeserta.setFont(cr.getCustomFont());
        		    vfm.add(hfmPeserta);
        		    vfm.add(gfmOrig);
		            
		    		// klaim
		    		if (intCekKlaim == 1) {

		    			HorizontalFieldManager hfmKlaim = cr.getHeaderRibbon("DAFTAR KLAIM", 0);
		    			hfmKlaim.setFont(cr.getCustomFont());
	        		    vfm.add(hfmKlaim);
		    			
	        		    VerticalFieldManager vfmColorKlaim = new VerticalFieldManager(Field.USE_ALL_WIDTH){
            	            public void paint(Graphics graphics){
            	                graphics.setBackgroundColor(Integer.parseInt("E0FFFF", 16));
            	                graphics.clear();
            	                super.paint(graphics);
            	            }
            	        };
            	        vfmColorKlaim.setFont(cr.getCustomFont());
            	        vfmColorKlaim.add(gfmKlaim);
            	        
            	        vfmColorKlaim.add(new LabelField("Kondisi: "));
            	        vfmColorKlaim.add(new RichTextField(strKondisi));
            	        vfmColorKlaim.add(new LabelField(" "));
            	        
            	        vfmColorKlaim.add(new LabelField("Kendala: "));
            	        vfmColorKlaim.add(new RichTextField(strKendala));
            	        vfmColorKlaim.add(new LabelField(" "));
            	        
            	        vfmColorKlaim.add(new LabelField("Keterangan: "));
            	        vfmColorKlaim.add(new RichTextField(strKeterangan));
            	        vfmColorKlaim.add(new LabelField(" "));
            	        
		    			vfm.add(vfmColorKlaim);
		    			
		    			LabelField lblRecord = new LabelField(" " + strRecNo + "/" + strMaxNo + " ");
	        	        HorizontalFieldManager btPrevNext = new HorizontalFieldManager(Field.USE_ALL_WIDTH){
	        	            public void paint(Graphics graphics){
	        	                graphics.setBackgroundColor(Integer.parseInt("b3b3b3", 16));
	        	                graphics.clear();
	        	                super.paint(graphics);
	        	            }
	        	        };
	        	        btPrevNext.setFont(cr.getCustomFont());
	        	        btPrevNext.add(btPrevKlaim);
	        	        btPrevNext.add(lblRecord);
		    			btPrevNext.add(btNextKlaim);
		    			vfm.add(btPrevNext);
		    			
//		    			vfm.add(new NullField(NullField.FOCUSABLE));
//		    			vfm.add(new NullField(NullField.FOCUSABLE));
		    		}
				}
				catch (Exception exp) {
					// nothing
				}
			}
		} else {
			synchronized (UiApplication.getEventLock()) {
				Dialog.alert("Unknown content type: " + contentType);
			}
		}
	}
	
	/**
	 * membaca result berupa xml 
	 */
	private void displayNode( Node node, int depth ) {
		
		// ==> element artinya diapit oleh xml-tag, misal <nama>novan</nama>
        if ( node.getNodeType() == Node.ELEMENT_NODE ) {
            
        	StringBuffer buffer = new StringBuffer();
            indentStringBuffer( buffer, depth );
        	NodeList childNodes = node.getChildNodes();
            int numChildren = childNodes.getLength();
            Node firstChild = childNodes.item( 0 );
            
            // ==> 1 child artinya satu sub-element
            // bagian ini berusaha mencari text di antara element
            // bila menemukan element baru / sub-element, maka dilihat bagian dalamnya.. rekursif
            // bila menemukan text, akan ditampilkan
            if ( numChildren == 1 && firstChild.getNodeType() == Node.TEXT_NODE ) {
            	
            	if (strRootName.equalsIgnoreCase("Peserta")) {
            		
	            	// bandingkan dengan xml-nya
	        		if (node.getNodeName().equalsIgnoreCase("NoPolis")) {
	        			strHidNoPolis = firstChild.getNodeValue();
	            		gfmOrig.add(new LabelField("No Polis"), Field.FIELD_LEFT);
		            	gfmOrig.add(new LabelField(" : "), Field.FIELD_HCENTER);
		            	gfmOrig.add(new LabelField(strHidNoPolis), Field.FIELD_LEFT);
	            	} else if (node.getNodeName().equalsIgnoreCase("NamaPemilik")) {
	            		gfmOrig.add(new LabelField("Nama Pemilik"), Field.FIELD_LEFT);
		            	gfmOrig.add(new LabelField(" : "), Field.FIELD_HCENTER);
		            	gfmOrig.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
	            	} else if (node.getNodeName().equalsIgnoreCase("NoPlat")) {
	            		strHidNoPlat = firstChild.getNodeValue();
	            		gfmOrig.add(new LabelField("No Plat Kendaraan"), Field.FIELD_LEFT);
		            	gfmOrig.add(new LabelField(" : "), Field.FIELD_HCENTER);
		            	gfmOrig.add(new LabelField(strHidNoPlat), Field.FIELD_LEFT);
	            	} else if (node.getNodeName().equalsIgnoreCase("NoRangka")) {
	            		strHidNoRangka = firstChild.getNodeValue();
	            		gfmOrig.add(new LabelField("No Rangka Kendaraan"), Field.FIELD_LEFT);
		            	gfmOrig.add(new LabelField(" : "), Field.FIELD_HCENTER);
		            	gfmOrig.add(new LabelField(strHidNoRangka), Field.FIELD_LEFT);
	            	} else if (node.getNodeName().equalsIgnoreCase("NoMesin")) {
	            		strHidNoMesin = firstChild.getNodeValue();
	            		gfmOrig.add(new LabelField("No Mesin Kendaraan"), Field.FIELD_LEFT);
		            	gfmOrig.add(new LabelField(" : "), Field.FIELD_HCENTER);
		            	gfmOrig.add(new LabelField(strHidNoMesin), Field.FIELD_LEFT);
	            	}
	            	
            	} else if (strRootName.equalsIgnoreCase("Klaim")) {
            		
            		if (node.getNodeName().equalsIgnoreCase("RecNo")) {
            			intCekKlaim = 1;
            			strRecNo = firstChild.getNodeValue();
            		} else if (node.getNodeName().equalsIgnoreCase("MaxNo")) {
            			strMaxNo = firstChild.getNodeValue();
            		} else if (node.getNodeName().equalsIgnoreCase("NoKlaim")) {
            			gfmKlaim.add(new LabelField("No Klaim"), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(" : "), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
            		} else if (node.getNodeName().equalsIgnoreCase("TglRegister")) {
            			gfmKlaim.add(new LabelField("Tgl Register"), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(" : "), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
            		} else if (node.getNodeName().equalsIgnoreCase("TglLapor")) {
            			gfmKlaim.add(new LabelField("Tgl Lapor"), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(" : "), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
            		} else if (node.getNodeName().equalsIgnoreCase("Bengkel")) {
            			gfmKlaim.add(new LabelField("Bengkel"), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(" : "), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
            		} else if (node.getNodeName().equalsIgnoreCase("Kondisi")) {
            			strKondisi = firstChild.getNodeValue();
            		} else if (node.getNodeName().equalsIgnoreCase("Kendala")) {
            			strKendala = firstChild.getNodeValue();
            		} else if (node.getNodeName().equalsIgnoreCase("Keterangan")) {
            			strKeterangan = firstChild.getNodeValue();
            		} else if (node.getNodeName().equalsIgnoreCase("StatusKlaim")) {
            			gfmKlaim.add(new LabelField("Status Klaim"), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(" : "), Field.FIELD_LEFT);
            			gfmKlaim.add(new LabelField(firstChild.getNodeValue()), Field.FIELD_LEFT);
            		}
            		
            		btPrevKlaim = new CustomButton(" << ", Color.BLACK, Color.LIGHTGRAY, Color.YELLOW, Color.RED, 0);
            		btPrevKlaim.setChangeListener(prevListener);
            		
            		btNextKlaim = new CustomButton(" >> ", Color.BLACK, Color.LIGHTGRAY, Color.YELLOW, Color.RED, 0);
            		btNextKlaim.setChangeListener(nextListener);
            		
            	}
            	
            } else if (numChildren > 1) {
            	
                // ==> lebih dari 1 children artinya ada lebih dari satu sub-element
                //buffer.append( node.getNodeName() );
                //add( new RichTextField( buffer.toString() ) ); // dimatikan supaya tidak menuliskan nama node -nya
            	strRootName = node.getNodeName();
            	
            	// Recursively visit all this node's children.
                // ==> rekursif, panggil diri sendiri untuk menampilkan isinya
                for ( int i = 0; i < numChildren; ++i ) {
                    displayNode( childNodes.item( i ), depth + 1 );
                }
                
            } else if (numChildren == 0)  {
            	for ( int i = 0; i < numChildren; ++i ) {
                    displayNode( childNodes.item( i ), depth + 1 );
                }
            }
            
        } else {
        	
            // ==> bukan element, artinya tidak diapit oleh xml-tag.. berarti ini text-node
            // ==> pada aplikasi ini, tidak akan ada text-node.. karena semua akan memakai tag..
        	// ==> jadi sebetulnya bagian ini bisa dihapus..
            String nodeValue = node.getNodeValue();
            if ( nodeValue.trim().length() != 0 )  {
                StringBuffer buffer = new StringBuffer();
                indentStringBuffer( buffer, depth );
                buffer.append( '"' ).append( nodeValue ).append( '"' );
                vfm.add(new LabelField(buffer.toString(), Field.USE_ALL_WIDTH));
            }
            
        }
    }
    
	/**
	 * request gagal 
	 */
	public void requestFailed(final String message) {
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				Dialog.alert("Request failed. Reason: " + message);
			}
		});
	}
	
	/**
	 * Untuk Keperluan baca XML 
	 */
	private static void indentStringBuffer( StringBuffer buffer, int depth ) {
        int indent = depth * _tab;
        for ( int i = 0; i < indent; ++i ) {
            buffer.append( ' ' );
        }
    }
	
	/**
     * Action Listener btPrev
     */
    FieldChangeListener prevListener = new FieldChangeListener() {
	     public void fieldChanged(Field field, int context) {
	    	 int intNewNum = Integer.parseInt(strRecNo) - 1;
	    	 int intMaxNo = Integer.parseInt(strMaxNo);
	    	 if (intNewNum < 1) {
	    		 intNewNum = 1;
	    	 }
            strRecNo = String.valueOf(intNewNum);
            strMaxNo = String.valueOf(intMaxNo);
            fnViewKlaimScreen();
        }
   };
   
   /**
    * Action Listener btNext
    */
   FieldChangeListener nextListener = new FieldChangeListener() {
	     public void fieldChanged(Field field, int context) {
	    	 int intNewNum = Integer.parseInt(strRecNo) + 1;
	    	 int intMaxNo = Integer.parseInt(strMaxNo);
	    	 if (intNewNum > intMaxNo) {
	    		 intNewNum = intMaxNo;
	    	 }
            strRecNo = String.valueOf(intNewNum);
            strMaxNo = String.valueOf(intMaxNo);
            fnViewKlaimScreen();
        }
   };
   
   /**
    * View Klaim
    */
   private void fnViewKlaimScreen() {
	   CallMBUServlet cms = new CallMBUServlet();
	   cms.fnCallMBUServlet(this, strHidNoPlat, strHidNoPolis, strHidNoRangka, strHidNoMesin, strRecNo, strMaxNo);
	}
}
